package com.mayikt.jwt;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Base64;

/**
 * @ClassName Test009
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class Test009 {
    private static String SIGN_KEY = "mayikt";

    public static void main(String[] args) {
        // head /payload/ sign
        JSONObject header = new JSONObject();
        header.put("alg", "HS256");
        // payload
        JSONObject payload = new JSONObject();
        payload.put("phone", "18611011111");
        payload.put("time", 60);
        String paloadStr = payload.toJSONString();
        //sign第三组成：payload实现MD5加密
        String sign = DigestUtils.md5Hex(paloadStr + SIGN_KEY);
        String jwt = Base64.getEncoder().encodeToString(header.toJSONString().getBytes()) + "." +
                Base64.getEncoder().encodeToString(paloadStr.getBytes()) + "." + sign;
        System.out.println(jwt + "");
//        jwt += "msfashfsajzxgzxfnjasfgasfsahfgsafhasgfsa";

        // jwt的解密
        String[] split = jwt.split("\\.");
        String payLoad = new String(Base64.getDecoder().decode(split[1].getBytes()));

        System.out.println(DigestUtils.md5Hex(payLoad + SIGN_KEY).equals(split[2]));
        System.out.println(payLoad);


    }
}
